package com.rongchuan.wt.service.impl;

import com.fasterxml.jackson.databind.ser.impl.MapEntrySerializer;
import com.rongchuan.wt.constant.MessageContant;
import com.rongchuan.wt.entity.Department;
import com.rongchuan.wt.entity.Employee;
import com.rongchuan.wt.exception.DepartmentException;
import com.rongchuan.wt.mapper.DepartmentMapper;
import com.rongchuan.wt.service.IDepartmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /*
     * 添加部门
     */
    @Override
    public void addDepartment(Department department) {
        //1、先查询所有部门的名称
         List<String>  name = departmentMapper.list();
         //2、判断部门名称是否重复
         for (String s : name) {
             if (s.equals(department.getName())){
                 throw new DepartmentException(MessageContant.DEP_NAME_REPEAT);
             }
         }
         department.setCreateTime(LocalDateTime.now());
         departmentMapper.insert(department);
    }

    /**
     * 查询部门
     * @param department
     * @return
     */
    @Override
    public List<Department> queryDepartment(Department department) {

        List<Department> departmentList = departmentMapper.select(department);

        return departmentList;
    }

    @Override
    public void updateDepartment(Department department) {
        //判断部门编码是否可以修改
        if (StringUtils.isNotEmpty(department.getCode())){
            throw new DepartmentException(MessageContant.DEP_CODE_NOT_EDIT);
        }
        //修改时间
        department.setUpdateTime(LocalDateTime.now());
        departmentMapper.update(department);
    }

    @Override
    public void deleteDepartment(Long id) {
        //1、先根据部门id关联查询部门员工表，如果存在部门员工则禁止删除
        int count = departmentMapper.selectEmployeeList(id);

        if (count > 0){
            throw new DepartmentException(MessageContant.DEP_EMP_EXIST);
        }

        departmentMapper.delete(id);
    }
}
